<?php

defined('SYSPATH') or die('No direct script access.');

class News {

    private static $instances;
    private $data;

    public static function & instances($id = 0) {

        if (!isset(self::$instances[$id])) {
            $class = __CLASS__;
            self::$instances[$id] = new $class($id);
        }
        return self::$instances[$id];
    }

    public function __construct($id) {

        $this->data = NULL;
        $this->_load($id);
    }

    public function _load($id) {

        if (!$id)
            return FALSE;

        $result = ORM::factory('new')
                ->where('id_news', '=', $id)
                ->find()
                ->as_array();

        $this->data = $result ? $result : array();
    }

    public function get($key = NULL) {

        if (is_null($key)) {
            return $this->data;
        } else {
            return isset($this->data[$key]) ? $this->data[$key] : NULL;
        }
    }

    public function set($data) {

        $news = ORM::factory('new');
        $news->values($data);
        if ($news->check()) {
            $news->save();
            if ($news->saved()) {
                return true;
            }
        }

        return false;
    }

  

    public function update($data) {
        $news = ORM::factory('new')
                ->where('id_news', '=', $this->data['id_news'])
                ->find();

        if (!$news->loaded()) {
            return false;
        } else {
            $news->values($data);
            if ($news->check()) {
                $news->save();
                if ($news->saved()) {
                    return true;
                }
            }
        }
    }

    public function delete() {
        $news = ORM::factory('new', $this->data['id_news']);
        if ($news->loaded()) {
            return $news->delete();
        } else {
            return FALSE;
        }
    }

     public function get_news($offset = 0, $limit = 0, $orderby = '', $category = '0')
    {
        if ($orderby == '')
        {
            $orderby = 'i.position,i.updatetime desc';
        }
        $tbl = 'xuwenweb_news i';
        $where = "i.id_news !='0'";

        if ($category != '0')
        {
            $tbl .= ',xuwenweb_categories g';
            $where .=' and i.id_category=g.id_category and g.id_category=' . $category;
        }

        $sql = "SELECT * FROM " . $tbl . " WHERE " . $where . " order by " . $orderby.' limit '.$limit;
        $value_result = DB::query(1, $sql)->execute()->as_array();


        if (count($value_result))
        {
            return $value_result;
        }
        else
        {
            return array();
        }
    }

}

